package com.ruoyi.thoroughfare.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.thoroughfare.domain.AppUser;
import com.ruoyi.thoroughfare.domain.vo.AppShareVo;
import com.ruoyi.thoroughfare.service.IAppShareService;
import com.ruoyi.thoroughfare.service.IAppUserService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.redis.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.sms4j.provider.enumerate.SupplierType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.time.Duration;
import java.util.LinkedHashMap;


/**
 * app注册控制器
 * 前端访问路由地址为:/app/register
 *
 * @author Zach
 * @date 2023-11-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/register")
public class AppRegisterController extends BaseController {
    private final IAppUserService iAppUserService;

    private final IAppShareService iAppShareService;



    @PostMapping("registerAppUser")
    public  R<Object>  registerAppUser(@NotBlank(message = "{user.phonenumber.not.blank}") String phone,@NotBlank(message = "验证码不能为空")String code,@NotBlank(message = "密码不能为空") String password,@NotBlank(message = "邀请码不能为空") String yqm) {
        String key = CacheConstants.CAPTCHA_CODE_KEY + phone;
        String yzcode =RedisUtils.getCacheObject(key);
        if (code.equals(yzcode)){
            AppUser appUser=iAppUserService.queryByPhone(phone);
            if (appUser==null){
                AppShareVo appShareVo=iAppShareService.queryByCode(yqm);
                if (appShareVo!=null){
                    AppUser appUserBo=new AppUser();
                    appUserBo.setPhoneNumber(phone);
                    appUserBo.setUserName(phone);
                    appUserBo.setUserPassword(BCrypt.hashpw(password));
                    appUserBo.setUserLevel(0L);
                    appUserBo.setUserType(0L);
                    appUserBo.setUserRealStatus(0L);
                    appUserBo.setSuperUserId(appShareVo.getUserId());
                    appUserBo.setCertificationStatus(0L);
                    appUserBo.setStatus(1L);
                    iAppUserService.saveUser(appUserBo);
                    return R.ok("注册成功");
                }else{
                    return R.fail("邀请码不正确，请核对后再试");
                }
            }else{
                return R.fail("该手机号已注册账户");
            }
        }
        return R.fail("验证码不正确，请重新输入");
    }

    /**
     *  注册页面验证码获取
     *
     * @author Zach
     * @param phones
     * @return com.ruoyi.common.core.domain.R<java.lang.Object>
     * @date 2023/11/16 18:15
     */

    @PostMapping("/sendCodeMsg")
    public  R<Object>  sendCodeMsg(@NotBlank(message = "{user.phonenumber.not.blank}") String phones) {
        long EXPIRATION=Constants.CAPTCHA_EXPIRATION;
//        long EXPIRATION=30;
            AppUser appUser=iAppUserService.queryByPhone(phones);
            if (appUser==null){
                String key = CacheConstants.CAPTCHA_CODE_KEY + phones;
                String code = RandomUtil.randomNumbers(4);
                RedisUtils.setCacheObject(key, code, Duration.ofMinutes(EXPIRATION));
                // 验证码模板id 自行处理 (查数据库或写死均可)
                String templateId = "1630945";
                LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                map.put("1", code);
                map.put("2", String.valueOf(EXPIRATION));
                SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.TENCENT);
                SmsResponse smsResponse = smsBlend.sendMessage(phones, templateId, map);
                return R.ok("已发送验证码，验证码"+EXPIRATION+"分钟内有效",smsResponse);
//                return R.ok("");
            }else{
                return R.fail("该手机号已注册账户");
            }
    }

}
